package cn.edu.cqu.services.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.domains.TeacherInfo;
import cn.edu.cqu.services.TeacherInfoCRUD;

@Service("TeacherInfoCRUDHibernate")
public class TeacherInfoCRUDHibernate implements TeacherInfoCRUD {
	
	private HibernateTemplate ht;
	private Session session;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
		session = ht.getSessionFactory().openSession();
	}
	
	@Override
	public TeacherInfo getByID(String tID) {
		return ht.get(TeacherInfo.class, tID);
	}

	@Override
	@Transactional
	public TeacherInfo edit(TeacherInfo teacherInfo) {
		 return ht.merge(teacherInfo);
	}

	@Override
	@Transactional
	public void deleteByID(String tID) {
		TeacherInfo teacherInfo = this.getByID(tID);
		ht.delete(teacherInfo);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TeacherInfo> getAll(int pageNo, int pageSize) {
		String hql = "from TeacherInfo";
		Query query = session.createQuery(hql);
		return query.setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TeacherInfo> getByDepatment(String department, Integer pageNo, Integer pageSize) {
		String hql = "from TeacherInfo where tDepatment=?";
		Query query = session.createQuery(hql);
		query.setString(0, department);
		return query.setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
	}

}
